import React from "react";
import FlvJs from "flv.js";

interface FlvProps {
  videoId: string,
  videoRef: string,
  videoUrl: string
}

export class Flv extends React.Component<FlvProps, {}> {

  private flvPlayer?: FlvJs.Player;
  private readonly mediaDataSource: FlvJs.MediaDataSource;
  private readonly config?: FlvJs.Config;

  constructor(props: any) {
    super(props);
    this.mediaDataSource = {
      type: 'flv',
      url: this.props.videoUrl,
      hasAudio: true,
      hasVideo: true,
      isLive: true,
    }
    this.config = {
      enableStashBuffer: false,
      lazyLoad: false,
      isLive: true,
      autoCleanupSourceBuffer: true,
    }
  }

  render() {
    return <video id={this.props.videoId}
                  ref={this.props.videoRef}
                  controls={true}
                  style={{height: '100%', width: '100%',}}
    />
  }

  componentDidMount() {
    const videoElement = window.document.getElementById(this.props.videoId);
    this.flvPlayer = FlvJs.createPlayer(this.mediaDataSource, this.config);
    this.flvPlayer.attachMediaElement(videoElement as HTMLMediaElement);
    this.flvPlayer.load();
    this.flvPlayer.play();
  }

  componentWillUnmount() {
    if (this.flvPlayer !== undefined) {
      this.flvPlayer.destroy();
    }
  }
}